import 'package:flutter/material.dart';
import 'package:flutter_deer/account/models/city_entity.dart';
import 'package:flutter_deer/mvp/base_page_presenter.dart';
import 'package:flutter_deer/net/net.dart';
import 'package:flutter_deer/login/iview/login_iview.dart';
import 'package:flutter_deer/shop/models/user_entity.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:crypto_x/crypto_x.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:sp_util/sp_util.dart';

class LoginPagePresenter extends BasePagePresenter<LoginIMvpView> {

  @override
  void initState() {

  }

  Future<dynamic> loginByUsername(String username,String password) async {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final key = CipherKey.fromUTF8(Constant.encryptPasswordKey);
      final iv = CipherIV.fromUTF8(Constant.encryptPasswordKey);
      var aes = AES(key: key, mode: AESMode.cfb, padding: null);
      CryptoBytes encrypted = aes.encrypt(
          CryptoBytes.fromUTF8(password.trim()), iv: iv);
      final UserPasswordLoginEntity loginEntity = UserPasswordLoginEntity(
          username: username.trim(), password: encrypted.base64);
      final Map<String, dynamic> params = <String, dynamic>{};
      params['grant_type'] = 'password';
      requestNetwork<UserTokenEntity>(Method.post,
          url: HttpApi.loginByUsername,
          params: loginEntity.toJson(),
          queryParameters: params,
          onSuccess: (data) {
            SpUtil.putString(Constant.tokenType, data!.tokenType.nullSafe);
            SpUtil.putString(Constant.accessToken, data!.accessToken.nullSafe);
            SpUtil.putString(
                Constant.refreshToken, data!.refreshToken.nullSafe);
            SpUtil.putString(Constant.perfect, data!.perfect.nullSafe);
            SpUtil.putString(Constant.phone, username);
            SpUtil.putString(Constant.password, encrypted.base64);
            view.setUserToken(data);
          },
          onError: (code, msg) {

          }
      );
    });
  }
 
  void testListData() {
    /// 测试返回List类型数据解析
    asyncRequestNetwork<List<CityEntity>>(Method.get,
      url: HttpApi.subscriptions,
      onSuccess: (data) {

      },
    );
  }
}
